import {create} from "zustand";
import {debounce, debounceNoArg} from "@/utils/Util.ts";
import {bgTransparencyStoreLocal, IThemeStoreData, themeStoreLocal} from "@/store/LocalStore.ts";

export interface IThemeStore {
    theme: IThemeStoreData
    defaultTheme: IThemeStoreData
    updateTheme: (data: IThemeStoreData) => void
    toDefault: () => void
    bgTransparency: number
    setBgTransparency: (bgTransparency: number) => void
}

export function isDarkMode() {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

const defaultThemeData: IThemeStoreData = {
    type: "default",
    color: "F988A4",
}

const useThemeStore = create<IThemeStore>((set) => {
    let data = themeStoreLocal.get()
    if (data == null) {
        data = defaultThemeData
        themeStoreLocal.set(data)
    }
    let data1 = bgTransparencyStoreLocal.get()
    if (data1 == null) {
        data1 = {bgTransparency: 0xcf}
    }
    return {
        theme: data,
        defaultTheme: defaultThemeData,
        updateTheme: debounce((data: IThemeStoreData) => {
            set({theme: data})
            themeStoreLocal.set(data)
        }),
        toDefault: debounceNoArg(() => {
            set({theme: defaultThemeData})
            themeStoreLocal.set(defaultThemeData)
        }),
        bgTransparency: data1.bgTransparency,
        setBgTransparency: (bgTransparency) => {
            set({bgTransparency})
            bgTransparencyStoreLocal.set({bgTransparency})
        },
    }
})

export default useThemeStore
